package com.atguigu.tingshu.common.service;

import com.alibaba.fastjson.JSON;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;

@Service
public class KafkaService {

    private static final Logger logger = LoggerFactory.getLogger(KafkaService.class);

    @Resource
    private KafkaTemplate kafkaTemplate;

    public boolean sendMessage(String value, String topic) {
        try {
            CompletableFuture send = kafkaTemplate.send(topic, value);
            send.get(); // 等待发送完成
            logger.debug("发送消息成功: topic={}，value={}", topic, JSON.toJSONString(value));
            return true;
        } catch (Exception e) {
            logger.error("发送消息失败: topic={}，value={}", topic, JSON.toJSONString(value), e);
            return false;
        }
    }
}
